package net.youpoint.dao.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import net.youpoint.core.PMF;
import net.youpoint.dao.QuestionDao;
import net.youpoint.entity.QuestionEntity;

import com.google.appengine.api.datastore.Key;

public class QuestionDaoImpl implements QuestionDao, Serializable {

	private static final long serialVersionUID = -4393929572369415361L;

	@SuppressWarnings("unchecked")
	@Override
	public List<QuestionEntity> listAll() {
		final List<QuestionEntity> res = new ArrayList<QuestionEntity>();

		final PersistenceManager pm = PMF.get().getPersistenceManager();

		final Query query = pm.newQuery(QuestionEntity.class);

		try {

			final List<QuestionEntity> results = (List<QuestionEntity>) query
					.execute();

			final Collection<QuestionEntity> collection = pm
					.detachCopyAll(results);
			res.addAll(collection);
		} finally {
			pm.close();
			query.closeAll();
		}

		return res;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<QuestionEntity> list() {
		final List<QuestionEntity> res = new ArrayList<QuestionEntity>();

		final PersistenceManager pm = PMF.get().getPersistenceManager();

		final Query query = pm.newQuery(QuestionEntity.class);

		try {

			query.setFilter("deleteDate == null");

			final List<QuestionEntity> results = (List<QuestionEntity>) query
					.execute();

			final Collection<QuestionEntity> collection = pm
					.detachCopyAll(results);
			res.addAll(collection);
		} finally {
			pm.close();
			query.closeAll();
		}

		return res;
	}

	@Override
	public QuestionEntity find(final Key key) {

		if (key == null) {
			return null;
		}

		QuestionEntity res = null;

		final PersistenceManager pm = PMF.get().getPersistenceManager();

		try {
			final QuestionEntity entity = pm.getObjectById(
					QuestionEntity.class, key);

			res = pm.detachCopy(entity);
		} finally {
			pm.close();
		}

		return res;
	}

	@Override
	public void save(final QuestionEntity question) {
		final PersistenceManager pm = PMF.get().getPersistenceManager();

		try {

			pm.makePersistent(question);
		} finally {
			pm.close();
		}
	}

	@Override
	public void markDeleted(final QuestionEntity question) {

		question.setDeleteDate(new Date());

		save(question);
	}

	@Override
	public void totalDelete(final QuestionEntity question) {
		final PersistenceManager pm = PMF.get().getPersistenceManager();

		try {

			pm.deletePersistent(question);
		} finally {
			pm.close();
		}
	}
}
